package com.iscc.maoke.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/upload_img.do")
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");

        List<FileItem> itemList = null;
        List<DiskFileItem> diskFileItems = new ArrayList<>();

        try {
            itemList = upload.parseRequest(request);
            System.out.println("itemList = " + itemList);

            for (FileItem fileItem : itemList) {
                if (fileItem.isFormField()) {
                    System.out.println(fileItem.getFieldName() + " : " + new String(fileItem.getString().getBytes("iso-8859-1"), "utf8"));
                } else {
                    DiskFileItem item = (DiskFileItem) fileItem;
                    diskFileItems.add(item);
                }
            }
            String path = request.getServletContext().getRealPath("img");
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            for (DiskFileItem diskFileItem : diskFileItems) {
                File tempFile = new File(dir, diskFileItem.getName());
                diskFileItem.write(tempFile);
            }


        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
